/**
 * 下载动作
 * @param {*} url 
 */
function download(url) {
	let a = document.createElement('a');
	// a.href = '/api/system/user/importTemplate'
	a.href = url
	a.click();
}

/**
 * 解析URL参数为对象
 * @param {*} url 
 */
function parseUrl(url) {
	let urlObj = {
		protocol: /^(.+)\:\/\//,
		host: /\:\/\/(.+?)[\?\#\s\/]/,
		path: /\w(\/.*?)[\?\#\s]/,
		query: /\?(.+?)[\#\/\s]/,
		hash: /\#(\w+)\s$/
	}
	url += ' '

	function formatQuery(str) {
		return str.split('&').reduce((a, b) => {
			let arr = b.split('=')
			a[arr[0]] = arr[1]
			return a
		}, {})
	}
	for (let key in urlObj) {
		let pattern = urlObj[key]
		urlObj[key] = key === 'query' ? (pattern.exec(url) && formatQuery(pattern.exec(url)[1])) : (pattern.exec(url) &&
			pattern.exec(url)[1])
	}
	return urlObj
}

function date2string(date) {
	const dt = new Date(date)
	var dateObj = {
		y: dt.getFullYear(),
		m: dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1).toString() : dt.getMonth() + 1,
		d: dt.getDate() < 10 ? '0' + (dt.getDate()).toString() : dt.getDate(),
		h: dt.getHours() < 10 ? '0' + (dt.getHours()).toString() : dt.getHours(),
		i: dt.getMinutes() < 10 ? '0' + (dt.getMinutes()).toString() : dt.getMinutes(),
		s: dt.getSeconds() < 10 ? '0' + (dt.getSeconds()).toString() : dt.getSeconds(),
		a: dt.getDay()
	}
	const week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
	const timeStr = dateObj.y + '-' + dateObj.m + '-' + dateObj.d + ' ' + dateObj.h + ':' + dateObj.i + ' ' + week[
		dateObj.a]
	const dateTimeStr = dateObj.y + '-' + dateObj.m + '-' + dateObj.d + ' ' + dateObj.h + ':' + dateObj.i
	const timingStr = dateObj.h + ':' + dateObj.i
	const dateStr = dateObj.y + '-' + dateObj.m + '-' + dateObj.d
	return { timeStr, dateStr, timingStr, dateTimeStr }
}

function formatDate(time, format) {
	let date = time || new Date();
	let map = {
		'y': date.getFullYear(),
		'M': date.getMonth() + 1, //month
		'd': date.getDate(), //date
		'H': date.getHours(), //hours
		'm': date.getMinutes(), //minutes
		's': date.getSeconds() //seconds
	};
	for (let i in map) {
		if (map.hasOwnProperty(i)) {
			if (map[i] < 10) {
				map[i] = '0' + map[i];
			}
		}
	}
	format = format || 'yyyy-MM-dd HH:mm:ss';
	let reg = new RegExp('y+|M+|d+|H+|m+|s+', 'g');
	let regY = new RegExp('y');
	format = format.replace(reg, function(v) {
		let old = v;
		if (regY.test(v)) {
			let y = "" + map['y'];
			let len = 4 - v.length;
			old = y.substr(len);
		} else {
			let key = v.substr(0, 1);
			old = map[key];
		}
		return old;
	});
	return format;
}

export default {
	download,
	parseUrl,
	date2string,
	formatDate
}